﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;

namespace HYCodeBase.XmlUtility
{
	public class XmlNodeTransformNoneCollectionNodeHanlder
	{
		public bool TryTransformToXmlNode(object inputObject, XmlDocument useXmlDocument, out XmlNode creatNode)
		{
			creatNode = null;
			if (inputObject == null || useXmlDocument == null)
			{
				return false;
			}
			XmlNodeInformationBean xmlNodeInformationBean;
			if (!this.TryTransformToXmlNodeInformation(inputObject, out xmlNodeInformationBean))
			{
				return false;
			}
			creatNode = xmlNodeInformationBean.ToXmlNode(ref useXmlDocument);
			return true;
		}

		private bool TryTransformToXmlNodeInformation(object inputObject, out XmlNodeInformationBean creatBean)
		{
			creatBean = null;
			bool result;
			try
			{
				Type type = inputObject.GetType();
				if (!this.m_cache.ContainsKey(type))
				{
					this.m_cache.Add(type, new TypeXmlAttributeBean(type));
				}
				TypeXmlAttributeBean typeXmlAttributeBean = this.m_cache[type];
				if (typeXmlAttributeBean.UseClassAttribute == null || string.IsNullOrWhiteSpace(typeXmlAttributeBean.UseClassAttribute.ElementNodeName))
				{
					result = false;
				}
				else
				{
					creatBean = new XmlNodeInformationBean();
					creatBean.StrNodeName = typeXmlAttributeBean.UseClassAttribute.ElementNodeName;
					creatBean.LstSubNodes = new List<XmlNodeInformationBean>();
					creatBean.LstKvpAttribute = new List<KeyValuePair<string, string>>();
					foreach (KeyValuePair<PropertyInfo, XmlPropertyAttribute> keyValuePair in typeXmlAttributeBean.UsePropertyDic)
					{
						if (!string.IsNullOrWhiteSpace(keyValuePair.Value.UseXmlAttributeName))
						{
							string useXmlAttributeName = keyValuePair.Value.UseXmlAttributeName;
							string value = keyValuePair.Key.GetValue(inputObject).ToString();
							creatBean.LstKvpAttribute.Add(new KeyValuePair<string, string>(useXmlAttributeName, value));
						}
					}
					foreach (PropertyInfo propertyInfo in typeXmlAttributeBean.LstCollectionProperty)
					{
						foreach (object inputObject2 in (propertyInfo.GetValue(inputObject) as IEnumerable))
						{
							XmlNodeInformationBean item;
							if (this.TryTransformToXmlNodeInformation(inputObject2, out item))
							{
								creatBean.LstSubNodes.Add(item);
							}
						}
					}
					result = true;
				}
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private Dictionary<Type, TypeXmlAttributeBean> m_cache = new Dictionary<Type, TypeXmlAttributeBean>();
	}
}
